import React, { Component } from "react";
import Form from "./Form";
import List from "./List";

class App extends Component {
  state = {
    list: [
      {
        id: 1,
        name: "zhangmou",
        checked: false,
      },
      {
        id: 2,
        name: "junmou",
        checked: false,
      },
    ],
    globalChecked: false,
  };

  getItem = (v) => {
    // console.log(v);
    this.setState((prevState) => {
      return {
        list: [
          ...prevState.list,
          { id: new Date().getTime(), name: v, checked: false },
        ],
      };
    });
  };

  removeItem = (id) => {
    this.setState((prevState) => {
      return {
        list: prevState.list.filter((item) => item.id !== id),
      };
    });
  };

  changeChecked = (id, v) => {
    const newArr = this.state.list.map((item) => {
      if (item.id === id) {
        return { ...item, checked: v };
      } else {
        return item;
      }
    });
    this.setState({
      list: newArr,
    });
  };

  plRemove = () => {
    this.setState((prevState) => {
      return {
        list: prevState.list.filter((item) => !item.checked),
      };
    });
  };

  changeGlobalChecked = (e) => {
    this.setState((prevState) => {
      return {
        globalChecked: e.target.checked,
        list: prevState.list.map((item) => {
          return { ...item, checked: e.target.checked };
        }),
      };
    });
  };

  render() {
    return (
      <>
        <h2>todolist</h2>
        <Form onGetItem={this.getItem} />
        <List
          list={this.state.list}
          onRemoveItem={this.removeItem}
          onChangeChecked={this.changeChecked}
        />
        <div>
          全选:{" "}
          <input
            type="checkbox"
            checked={this.state.globalChecked}
            onChange={this.changeGlobalChecked}
          />
        </div>
        <button onClick={this.plRemove}>批量删除</button>
      </>
    );
  }
}

export default App;
